package com.credithc.signature.facade.controller.fadada;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.credithc.baseserv.core.codes.CoreCodes;
import com.credithc.baseserv.core.message.Message;
import com.credithc.baseserv.core.message.MessageFactory;
import com.credithc.signature.common.mapper.FddAuthCompanyMapper;
import com.credithc.signature.common.mapper.FddAuthPersonMapper;
import com.credithc.signature.common.mapper.FddSealInfoMapper;
import com.credithc.signature.common.po.FddAuthCompany;
import com.credithc.signature.common.po.FddAuthPerson;
import com.credithc.signature.common.po.FddSealInfo;
import com.credithc.signature.common.ro.facade.FddAuthReq;
import com.credithc.signature.common.ro.facade.QueryAuthenticationStatusReq;
import com.credithc.signature.common.to.CallBackCompany;
import com.credithc.signature.facade.client.FadadaRemoteClient;
import com.credithc.signature.facade.service.FddParamVerifyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

/**
 * @desc: 法大大注册接口<br />
 * @author: Jingbo Hu<br/>
 * @time：2020年07⽉13⽇<br/>
 * @version：v1.0.0<br>
 */
@RestController
@RequestMapping("/api/signaturefacade/v1")
@Slf4j
public class FddAuthController {

    @Autowired
    MessageFactory messageFactory;

    @Resource
    FddSealInfoMapper fddSealInfoMapper;

    @Autowired
    FadadaRemoteClient remote;

    @Autowired
    FddParamVerifyService verifyService;

    @Autowired
    FddAuthPersonMapper fddAuthPersonMapper;

    @Autowired
    FddAuthCompanyMapper fddAuthCompanyMapper;


    /**
     * 注册&获取认证地址
     *
     * @param req
     * @return
     */
    @ResponseBody
    @PostMapping("/auth/register")
    public Message fddRegisterAndGetUrl(@RequestHeader String encryptKey, @RequestBody FddAuthReq req) {
        // 校验参数
        Message message = verifyService.verifyParams(req, encryptKey);
        int code = message.getCode();
        if (0 != code) {
            return message;
        }
        // 检查是否注册过
        Integer accountType = req.getAccountType();
        switch (accountType) {
            case 1:
                List<FddAuthPerson> fddAuthPeople = fddAuthPersonMapper.selectByOpenId(req.getOpenId());
                if (fddAuthPeople != null && fddAuthPeople.size() > 0) {
                    return messageFactory.getInstance(CoreCodes.CORE_SYS_ERROR, "openId已存在，该个人用户已经注册过");
                }
            case 2:
                List<FddAuthCompany> fddAuthCompanies = fddAuthCompanyMapper.selectByOpenId(req.getOpenId());
                if (fddAuthCompanies != null && fddAuthCompanies.size() > 0) {
                    return messageFactory.getInstance(CoreCodes.CORE_SYS_ERROR, "openId已存在，该企业用户已经注册过");
                }
            default:
        }
        // 注册
        Message message1 = remote.register(req);
        int code1 = message1.getCode();
        if (1 != code1) {
            return message1;
        }
        // 获取实名认证地址
        String customerId = message1.getData().toString();
        req.setCustomerId(customerId);
        Message message2 = remote.getAuthUrl(req);
        int code2 = message2.getCode();
        if (0 != code2) {
            return message2;
        }
        return message2;
    }

    /**
     * 获取认证状态
     *
     * @param req
     * @return
     */
    @ResponseBody
    @PostMapping("/auth/queryStatus")
    public Message queryStatus(@RequestHeader String encryptKey, @RequestBody @Valid QueryAuthenticationStatusReq req) {
        // 校验参数
        Message message = verifyService.verifyParams9(req, encryptKey);
        int code = message.getCode();
        if (0 != code) {
            return message;
        }
        Message message1 = remote.queryStatus(req);
        //企业认证返回sealCode
        try {
            if (req.getAccountType() !=1){
                Object data = message1.getData();
                String s = JSONObject.toJSONString(data);
                CallBackCompany.DataBean data1 = JSONObject.parseObject(s, CallBackCompany.DataBean.class);
                CallBackCompany.DataBean.CompanyBean company = data1.getCompany();
                String status = company.getStatus();
                if ("4".equals(status)){
                    FddAuthReq fddAuthReq = new FddAuthReq();
                    fddAuthReq.setChannelNo(req.getChannelNo());
                    fddAuthReq.setSealSource(2);
                    String keyName = company.getCompanyName().substring(0, 4);
                    StringBuilder builder = new StringBuilder();
                    for (int i = 0; i < 4; i++) {
                        builder.append("_").append(keyName.charAt(i));
                    }
                    builder.append("_");
                    fddAuthReq.setKeyWords(builder.toString());
                    List<FddSealInfo> sealInfo = fddSealInfoMapper.selectByCodeOrKeyWords(fddAuthReq);
                    FddSealInfo fddSealInfo = sealInfo.get(0);
                    String sealCode = fddSealInfo.getSealCode();
                    data1.setSealCode(sealCode);
                    message1.setData(data1);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return message1;
    }


    /**
     * 修改用户信息
     *
     * @param req
     * @return
     */
    @ResponseBody
    @PostMapping("/auth/modifyUserInfo")
    public Message modifyUserInfo(@RequestHeader String encryptKey, @RequestBody @Valid FddAuthReq req) {
        // 校验参数
        Message message = verifyService.verifyParams6(req, encryptKey);
        int code = message.getCode();
        if (0 != code) {
            return message;
        }
        return remote.modifyUserInfo(req);
    }

    /**
     * 查询用户信息
     *
     * @param req
     * @return
     */
    @ResponseBody
    @PostMapping("/auth/queryUserInfo")
    public Message queryUserInfo(@RequestHeader String encryptKey, @RequestBody @Valid FddAuthReq req) {
        // 校验参数
        Message message = verifyService.verifyParams8(req, encryptKey);
        int code = message.getCode();
        if (0 != code) {
            return message;
        }
        return remote.queryUserInfo(req);
    }

    /**
     * 查询公章信息
     * @param encryptKey
     * @param req
     * @return
     */
    @ResponseBody
    @PostMapping("/auth/querySealInfo")
    public Message querySealInfo(@RequestHeader String encryptKey, @RequestBody @Valid FddAuthReq req) {
        // 校验参数
        Message message = verifyService.verifyParams11(req, encryptKey);
        int code = message.getCode();
        if (0 != code) {
            return message;
        }
        return remote.querySealInfo(req);
    }
}
